<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in stu" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      stu: [
        { name: "李雷", age: 18, gender: "男" },
        { name: "韩梅梅", age: 16, gender: "女" },
      ],
      name: "",
      age: "",
      gender: "",
      editIndex: null,
    };
  },
  methods: {
    add() {
      if (!this.name || !this.age || !this.gender) {
        return alert("请输入内容");
      }
      let obj = {
        name: this.name,
        age: this.age,
        gender: this.gender,
      };
      if (this.editIndex !== null) {
        this.$set(this.stu, this.editIndex, obj);
        this.editIndex=null
      } else {
        this.stu.push(obj);
      }
      this.name = this.age = this.gender = "";
    },
    del(i) {
      this.stu.splice(i, 1);
    },
    edit(i) {
      this.name = this.stu[i].name;
      this.age = this.stu[i].age;
      this.gender = this.stu[i].gender;
      this.editIndex = i;
    },
  },
};
</script>
